package com.fast.develop.dm.plugin.table.exporter.listener;

import com.fast.develop.dm.core.context.ModuleContext;
import com.fast.develop.dm.core.event.ContextStartedEvent;
import com.fast.develop.dm.core.listener.ModuleListener;
import com.fast.develop.dm.integration.context.DefaultModuleContext;
import com.fast.develop.dm.plugin.table.exporter.PluginTableExporter;
import org.hibernate.boot.Metadata;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

/**
 * @author 莫寅
 * @createTime 2022-06-09 16:23
 * @desc：
 */
public class ContextStartedListener implements ModuleListener<ContextStartedEvent> {

    private PluginTableExporter tableExporter;

    @Override
    public void onEvent(ContextStartedEvent event) {
        ModuleContext moduleContext = event.getSource();
        DefaultModuleContext defaultModuleContext = (DefaultModuleContext)moduleContext;

        LocalSessionFactoryBean localSessionFactoryBean = defaultModuleContext.getBean(LocalSessionFactoryBean.class);

        Metadata metadata = localSessionFactoryBean.getMetadataSources().buildMetadata(
                localSessionFactoryBean.getConfiguration().getStandardServiceRegistryBuilder().build()
        );

        if(localSessionFactoryBean.getObject() instanceof SessionFactoryImpl){
            SessionFactoryImpl sessionFactory = (SessionFactoryImpl) localSessionFactoryBean.getObject();
            Dialect dialect = sessionFactory.getJdbcServices().getDialect();
            PluginTableExporter tableExporter = new PluginTableExporter(dialect, metadata);

            this.tableExporter = tableExporter;
        }
    }

    public PluginTableExporter getTableExporter() {
        return tableExporter;
    }
}
